<template>
  <div id="edit">
    <a-spin :spinning="display" size="large">
      <div style="border: 1px solid #ccc" v-if="flag">
        <!-- 工具栏 -->
        <Toolbar
            :editorId="editorId"
            style="width: 100%; display: flex; justify-content: center; background-color: #fff"
        />
        <!-- 标题-->
        <div class="editer-tit">
          <div class="tit-input">
            <input v-model="inuptTxt" placeholder="请输入标题"/>
          </div>
        </div>
        <!-- 编辑器 -->
        <div class="editor-body">
          <Editor
              :editorId="editorId"
              :defaultConfig="editorConfig"
              :defaultContent="getDefaultContent"
              @onChange="handleChange"
              style="height: 500px; width: 888px; margin: 0 auto; padding-left: 20px"
          />
        </div>
        <!-- 发布设置-->
        <div class="pub-settings">
          <div class="set-body">
            <h2>发布设置</h2>
            <div class="add">
              <p>文章标签</p>
              <div class="label">
                <button v-for="(item,i) in labelName" @click="delClick(i)">#{{ item }}<span>×</span></button>
              </div>
              <div id="components-dropdown-demo-placement">
                <template v-for="(placement, index) in placements" :key="placement">
                  <a-dropdown :placement="placement">
                    <a-button>#添加标签</a-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item v-for="(item,index) in labelData" @click="labelClick(item.label,index)">
                     <span target="_blank" rel="noopener noreferrer">
                       #{{ item.label }}
                     </span>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                  <br v-if="index === 2"/>
                </template>
              </div>
            </div>
            <p>(最多可以添加两个)</p>
          </div>
        </div>
        <div class="pub-operation">
          <div class="pub-body">
            <div class="put-by-left">
              <p>正文字数: <span>{{ txtNum }}</span>字</p>
            </div>
            <div class="put-by-right">
              <p>草稿保存于<span>1</span><span>小时</span>前</p>
              <button class="button" @click="putClick"><span>发布</span></button>
            </div>
          </div>
        </div>
      </div>
    </a-spin>


  </div>


</template>

<script>
import {SettingOutlined} from '@ant-design/icons-vue';
import {defineComponent, computed, onBeforeUnmount, ref, watch, getCurrentInstance, reactive} from 'vue'
import {Editor, Toolbar, getEditor, removeEditor} from '@wangeditor/editor-for-vue'
import cloneDeep from 'lodash.clonedeep'
import { DownOutlined } from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';
import router from "@/router";
import $store from "@/store"

export default defineComponent({
  name: "weeklyEdit",
  components: {Editor, Toolbar, SettingOutlined,DownOutlined},
  setup() {
    const token = $store.state.token
    const userId = $store.state.userInfo.id
    const editorId = `w-e-${Math.random().toString().slice(-5)}`
// 编辑将默认显示的内容
    const defaultContent = ref([])
    const getDefaultContent = computed(() => cloneDeep(defaultContent.value))


    const flag = ref(false)
    const display = ref(true);
// 模拟 ajax 异步获取内容 同时防止editer组件销毁时本身组件没有销毁，以免报错
    setTimeout(() => {
      flag.value = true
      display.value = false
      defaultContent.value = [
        {
          type: "paragraph",
          children: [{text: ""}],
        },
      ]
    }, 500)


// 编辑器配置
    const editorConfig = {
      placeholder: '请输入内容...',
      /* 菜单配置，下文解释 */
      MENU_CONF: {}
    }
const imgSrc = ref(null);
    editorConfig.MENU_CONF['uploadImage'] = {
      //服务端地址
      server: 'http://119.23.46.241:11900/api/v1/user/weekly/file',

      // form-data fieldName ，默认值 'wangeditor-uploaded-file'
      //文件名称
      fieldName: 'file',

      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024, // 1M

      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 5,
      //传值用户ID
      meta: {
        userId: userId
      },
      //请求头
      headers: {
        Authorization: token
      },
    //  获取后台返回参数
      onSuccess(file, res) {
          imgSrc.value = res.data.href
      }
    }
// 回调函数
    const txtNum = ref();
    const coEdit = ref();
    const coGhtml = ref();
    const inuptTxt = ref();
    const textBody = ref();

    const handleChange = (editor) => {
      console.log('change:', JSON.stringify(editor.children))
      coEdit.value = JSON.stringify(editor.children);
      coGhtml.value = editor.getHtml();
      txtNum.value = editor.getText().length;
      textBody.value = editor.getText();
      console.log(testBody.value)
    }


    onBeforeUnmount(() => {
      const editor = getEditor(editorId) // 获取 editor 实例
      if (editor == null) return
      editor.destroy() // 执行 API
    })


    let {proxy} = getCurrentInstance();
    //获取所有标签
    const labelData = ref([]);
    let labelName = reactive([]);
    const labelIndex = reactive([]);
    proxy.$request('get', '/api/v1/user/weekly/release', {}).then(res => {
      console.log(res)
      labelData.value = res.data
    })
    //点击获取标签id
    const labelClick = (name, i) => {
      //  获取的标签名另存为
      labelName.push(name)
      //调用去重方法
      unique(labelName)
      //添加当前id
      labelIndex.push(i + 1)
      //
      if (labelName.length > 2) {
        message.error(
            '文章标签最多添加两个:(',
            3,
        );
        labelName.pop();
      }
    }
    //数组去重
    const unique = (arr) => {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            message.error(
                '文章标签重复了:(',
                3,
            );
            arr.splice(j, 1);
            j--;
          }
        }
      }
    }
    const putClick = () => {
      proxy.$request('post', '/api/v1/user/weekly', {
        "title": inuptTxt.value,
        "edit": coEdit.value,
        "content": coGhtml.value,
        "label[0]": labelIndex[0],
        "label[1]": labelIndex[1],
        "background": imgSrc.value,
        "text":textBody.value
      }).then(res => {
        switch (res.code) {
          case 200:
            message.success(
                '周报发布成功:)',
                3,
            );
            removeEditor(editorId)
            router.push('/weekly/weeklySearch');
            break;
        }
      })
      console.log(coEdit.value);
    }
//    点击标签删除
    const delClick = (index) => {
      labelName.splice(index, 1);
    }
// 组件销毁时，及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = getEditor(editorId)
      if (editor == null) return

      // 销毁，并移除 editor
      editor.destroy()
      removeEditor(editorId)
    })

    return {
      editorId,
      toolbar,
      mode: 'default',
      getDefaultContent,
      handleChange,
      editorConfig,
      txtNum,
      inuptTxt,
      putClick,
      labelData,
      labelClick,
      placements: ['bottomRight'],
      flag,
      display,
      labelName,
      delClick
    };
  },
})
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less">
#edit {
  margin-top: 65px;
  width: 100%;

  .ant-spin {
    .ant-spin-dot {
      position: fixed;
      right: 50%;
      top: 50%;
    }
  }

  .pub-settings {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 45px;
    .set-body {
      width: 888px;
      height: 140px;
      background-color: #FFFFFF;
      padding: 20px;

      .add {
        display: flex;

        .label {
          button {
            margin-left: 17px;
            border-radius: 5px;

            span {
              font-size: 15px;
              color: #8B8B8B;
              margin-left: 10px;
            }
          }
        }

        button {
          color: #6777EF;
          border: none;
          cursor: pointer;
          padding: 5px;
          margin-left: 35px;

        }
      }

      h2 {
        font-weight: bold;
      }
    }
  }

  .editor-body {
    width: 888px;
    background-color: #FFFFFF;
    margin: 0 auto;
  }

  .editer-tit {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .tit-input {
      width: 888px;
      display: flex;
      justify-content: center;
      background-color: #fff;

      input {
        width: 838px;
        outline: none;
        border: none;
        border-bottom: 3px solid #F5F5F5;
        height: 120px;
        padding-left: 10px;
        font-size: 25px;
        font-weight: bold;
      }

      input:link {
        border: none;
      }
    }


  }

  .pub-operation {
    width: 100%;
    height: 55px;
    background-color: #fff;
    display: flex;
    justify-content: center;

    .pub-body {
      width: 1200px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .put-by-left {
        display: flex;
        align-items: center;

        p {
          margin: 0;
        }
      }

      .put-by-right {
        display: flex;
        align-items: center;

        p {
          margin: 0 20px 0 0;
        }
      }


    }
  }
}
</style>